#include <stdio.h>
#include <time.h>
#include "Semaphore.h"

Semaphore::Semaphore(uint32_t init) {
	sem_init(&sem_, 0, init);
}

Semaphore::~Semaphore() {
	sem_destroy(&sem_);
}

bool Semaphore::take(uint32_t timeout) {
	if (timeout == ~0L)
		return sem_wait(&sem_) == 0;
	else {
		timespec time;
		clock_gettime(CLOCK_REALTIME, &time);
		time.tv_sec += timeout / 1000;
		time.tv_nsec += (timeout % 1000) * 1000000L;
        if (time.tv_nsec >= 1000000000L) {
        	++time.tv_sec;
        	time.tv_nsec -= 1000000000L;
        }

		return sem_timedwait(&sem_, &time) == 0;
	}
}

void Semaphore::give() {
	sem_post(&sem_);
}


